#include "painter.h"
#include "ui_painter.h"
#include <qdebug.h>

const int RectX = 40;
const int RectY = 40;

Painter::Painter(BinaryTree tree, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Painter)
{
    ui->setupUi(this);

    this->tree = tree;
}

void Painter::paintEvent(QPaintEvent *event) {
    QPainter painter(this);
    painter.setPen(QPen(Qt::black,5));
    QFont font;
    font.setPixelSize(28);
    painter.setFont(font);
    int height = GetTreeHeight(tree);
    Queue que = CreateQueue();
    EnQueue(que, (QueueVal){*tree, (1 << (height - 1)) * RectX, RectY});
    while (!IsQueueEmpty(que)) {
        QueueVal v = DeQueue(que);
        painter.drawArc(QRectF(v.x, v.y, RectX, RectY), 0, 360 * 16);
        painter.drawText(QRectF(v.x, v.y, RectX, RectY), Qt::AlignCenter, QString(v.val.val));
        int h = v.y / RectY / 2 + 1;
        if (v.val.lchild != nullptr) {
            QLineF line(v.x + RectX / 2, v.y + RectY, v.x - RectX * ((1<<(height - h)) / 2) + RectX / 2, v.y + 2 * RectY);
            painter.drawLine(line);
            EnQueue(que, (QueueVal){*v.val.lchild, v.x - RectX * ((1<<(height - h)) / 2), v.y + 2 * RectY});
        }
        if (v.val.rchild != nullptr) {
            QLineF line(v.x + RectX / 2, v.y + RectY, v.x + RectX * ((1<<(height - h)) / 2) + RectX / 2, v.y + 2 * RectY);
            painter.drawLine(line);
            EnQueue(que, (QueueVal){*v.val.rchild, v.x + RectX * ((1<<(height - h)) / 2), v.y + 2 * RectY});
        }
    }
}

Painter::~Painter()
{
    DestoryTree(tree);
    delete ui;
}
